package cn.smile.business.msg.impl;

import cn.smile.bean.dto.msg.MsgConDTO;
import cn.smile.bean.entity.msg.EmailInfo;
import cn.smile.business.msg.IEmailInfoService;
import cn.smile.business.msg.IEmailTempService;
import cn.smile.commons.constant.NumberConstant;
import cn.smile.commons.domain.BaseServiceImpl;
import cn.smile.commons.enums.msg.MailCodeEnum;
import cn.smile.repository.msg.EmailInfoMapper;
import cn.smile.utils.SendMailUtil;
import cn.smile.utils.UserUtil;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import jakarta.annotation.Resource;
import java.time.LocalDateTime;

/**
 * @author smile-jt
 */
@Slf4j
@Service
public class EmailInfoServiceImpl extends BaseServiceImpl<EmailInfoMapper, EmailInfo> implements IEmailInfoService {

    @Resource
    private IEmailTempService tempService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean sendMail(MailCodeEnum codeEnum, Object entity, String receiveAdd) {
        log.info("[EmailInfoServiceImpl].[sendMail] ------> Send Mail Info Start, codeEnum = {}, receiveAdd = {} entity = {}", codeEnum, receiveAdd, JSON.toJSONString(entity));
        MsgConDTO mailCon = tempService.getMailCon(codeEnum, entity);
        EmailInfo info = new EmailInfo();
        info.setEmailTitle(mailCon.getMsgTitle());
        info.setEmailContent(mailCon.getMsgContent());
        info.setReceiveAdd(receiveAdd);
        info.setSendTime(LocalDateTime.now());
        info.setSendUserId(UserUtil.getUserInfo().getId());
        info.setTemplateCode(codeEnum.getSn());
        try {
            SendMailUtil.sendEmail(receiveAdd, info.getEmailTitle(), info.getEmailContent());
            info.setSendError(Boolean.FALSE);
        } catch (Exception e) {
            log.error("Send Email Error, e = ", e);
            info.setSendError(Boolean.TRUE);
            info.setErrorMsg(e.getMessage());
        }
        super.addBaseCol(info);
        int insertNum = baseMapper.insert(info);
        log.info("[EmailInfoServiceImpl].[sendMail] ------> Send Mail Info End, insertNum = {}", insertNum);
        return insertNum > NumberConstant.ZERO;
    }
}
